package cn.esbot.wx.mp.utils;

import org.apache.catalina.util.URLEncoder;
import org.apache.commons.codec.digest.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class BotInfoUtils {

    public static String getSignature(Map<String, Object> params, String appKey) {
        Map<String, Object> sortedParams = new TreeMap<>(params);
        Set<Map.Entry<String, Object>> entrys = sortedParams.entrySet();
        StringBuilder baseString = new StringBuilder();
        for (Map.Entry<String, Object> param : entrys) {
            if (param.getValue() != null && !"".equals(param.getKey().trim()) &&
                    !"sign".equals(param.getKey().trim()) && !"".equals(param.getValue())) {
                baseString.append(param.getKey().trim()).append("=")
                        .append(URLEncoder.DEFAULT.encode(param.getValue().toString(), StandardCharsets.UTF_8)).append("&");
            }
        }
        if (baseString.length() > 0) {
            baseString.deleteCharAt(baseString.length() - 1).append("&appKey=")
                    .append(appKey);
        }
        String sign = DigestUtils.md5Hex(baseString.toString().getBytes());
        return sign.toUpperCase();
    }

}
